package com.cssw.fyzb.busi.api.user;

import com.cssw.fyzb.busi.service.user.UserService;
import com.cssw.fyzb.busi.service.user.UserSourceService;
import com.cssw.fyzb.busi.util.CodeUtil;
import com.cssw.fyzb.busi.util.HashUtil;
import com.cssw.fyzb.core.model.dodb.User;
import com.cssw.fyzb.core.model.dodb.UserSource;
import com.ydn.appserver.Action;
import com.ydn.appserver.Request;
import com.ydn.appserver.Response;
import com.ydn.appserver.annotations.Function;
import com.ydn.appserver.annotations.Parameter;
import com.ydn.appserver.annotations.Type;
import com.ydn.simplecache.SimpleCache;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Objects;

import static com.cssw.fyzb.busi.cache.CacheKeys.forRegister;
import static com.cssw.fyzb.busi.util.Bizs.*;

@Function(description = "QQ登录参数", parameters = {
        @Parameter(name = "openid", type = Type.String, description = "openid", required = true),
        @Parameter(name = "userName", type = Type.String, description = "用户名", required = false),
        @Parameter(name = "nickName", type = Type.String, description = "用户昵称", required = false),
        @Parameter(name = "province", type = Type.String, description = "省", required = false),
        @Parameter(name = "city", type = Type.String, description = "市", required = false),
        @Parameter(name = "sex", type = Type.String, description = "性别", required = false),
        @Parameter(name = "avatar", type = Type.String, description = "用户头像", required = false),
        @Parameter(name = "mobile", type = Type.String, description = "用户手机号", required = true),
        @Parameter(name = "verifyCode", type = Type.String, description = "手机验证码", required = true),
        @Parameter(name = "inviteCode", type = Type.String, description = "邀请码", required = true)
})
@Component
public class LoginByQQ implements Action {

    @Autowired
    private UserService userService;

    @Autowired
    private UserSourceService userSourceService;

    @Autowired
    private SimpleCache simpleCache;

    @Override
    public Response execute(Request request) throws Exception {
        String openid = request.getString("openid");
        String userName = request.getString("userName");
        String nickName = request.getString("nickName");
        String province = request.getString("province");
        String city = request.getString("city");
        String sex = request.getString("sex");
        String avatar = request.getString("avatar");
        String inviteCode = request.getString("inviteCode");
        String mobile = request.getString("mobile");
        String verifyCode = request.getString("verifyCode");
        String cached = simpleCache.get(forRegister(mobile));
        try {
            // 校验验证码
            if (!verifyCode.equals(cached)) {
                return Response.fail(ERROR_VERIFY.message, ERROR_VERIFY.code);
            }
            User inviter = null;
            Long supUserId = null;
            if (StringUtils.isNotEmpty(inviteCode)) {
                supUserId = CodeUtil.decode(inviteCode);
                inviter = userService.getById(supUserId);
                if (inviter == null) {
                    return Response.fail(ERROR_INVITCODE.message, ERROR_INVITCODE.code);
                }
            }

            if (userService.getByMobile(mobile) != null) {
                return Response.fail(ERROR_REGISTERED.message, ERROR_REGISTERED.code);
            }

            UserSource userSource = userSourceService.getBySourceCode(openid);
            if (Objects.isNull(userSource)) {
                // 没有绑定用户请前往绑定
                // 保存用户
                Long userId = userService.saveQQ(supUserId, mobile, openid, userName, nickName, province, city, sex, avatar);
                //return Response.success("登录成功").put("userId", userId);

                String token = HashUtil.md5(userId + "" + System.currentTimeMillis());
                userService.saveCmfToken(userId, token);
                return Response.success().put("userId", userSource.getUserId()).put("token", token);
            } else {
                // 已经绑定用户信息直接登录
                String token = HashUtil.md5(userSource.getUserId() + "" + System.currentTimeMillis());
                userService.saveCmfToken(userSource.getUserId(), token);
                return Response.success().put("userId", userSource.getUserId()).put("token", token);
            }
        } catch (Exception e) {
            return Response.fail("用户登录失败");
        }
    }
}
